<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="站点名称" prop="id">
        <el-select v-model="queryParams.id" placeholder="请选择站点">
          <el-option
            v-for="item in stationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="刷卡时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="ageFilter">
        <el-checkbox v-model="queryParams.ageFilter" true-label="65+" false-label="">65岁及以上</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['jzzgl:skjl:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="recordList">
      <el-table-column label="站点名称" align="center" prop="stationName" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="身份证号" align="center" prop="idNumber" />
      <el-table-column label="年龄" align="center">
        <template #default="scope">
          {{ calculateAge(scope.row.birthday) }}
        </template>
      </el-table-column>
      <el-table-column label="输入方式" align="center">
        <template #default="scope">
          {{ scope.row.inputMethod === 0 ? '设备采集' : '手动输入' }}
        </template>
      </el-table-column>
      <el-table-column label="刷卡时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['jzzgl:skjl:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="刷卡记录详情" v-model="open" width="800px" append-to-body>
      <div class="detail-header">
        <div class="label">站点名称</div>
        <div class="content">{{ form.stationName }}</div>
      </div>
      
      <div class="detail-content">
        <div class="left-info">
          <div class="basic-info">
            <div class="info-row">
              <span class="label">姓名</span>
              <span class="value">{{ form.name }}</span>
            </div>
            <div class="info-row">
              <span class="label">性别</span>
              <span class="value">{{ form.gender }}</span>
            </div>
            <div class="info-row">
              <span class="label">民族</span>
              <span class="value">{{ form.nation }}</span>
            </div>
          </div>
        </div>
        <div class="right-photo">
          <img v-if="form.photo" :src="`data:image/bmp;base64,${form.photo}`" class="id-photo" />
        </div>
      </div>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="身份证号">{{ form.idNumber }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ form.birthday }}</el-descriptions-item>
        <el-descriptions-item label="发证机关">{{ form.issuingAuthority }}</el-descriptions-item>
        <el-descriptions-item label="有效期限">{{ form.validPeriod }}</el-descriptions-item>
        <el-descriptions-item label="发卡次数">{{ form.issueCount }}</el-descriptions-item>
        <el-descriptions-item label="刷卡时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="住址" :span="2">{{ form.address }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { listRecord, getRecord } from "@/api/jzzgl/record";
import { listStation } from "@/api/jzzgl/station";
import { ElMessage } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'

const loading = ref(false)
const total = ref(0)
const recordList = ref([])
const showSearch = ref(true)
const dateRange = ref([])
const stationOptions = ref([])

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  id: undefined,
  name: undefined,
  idCard: undefined,
  ageFilter: ''
})

const open = ref(false);
const form = ref({
  id: undefined,
  stationId: undefined,
  stationName: undefined,
  name: undefined,
  gender: undefined,
  nation: undefined,
  birthday: undefined,
  address: undefined,
  idNumber: undefined,
  issuingAuthority: undefined,
  validPeriod: undefined,
  communicationNumber: undefined,
  issueCount: 0,
  createTime: undefined,
  photo: undefined
});

// 获取站点列表（用于下拉选择）
const getStationOptions = async () => {
  try {
    const res = await listStation({ pageSize: 999 });
    console.log('站点列表数据:', res.rows);
    stationOptions.value = res.rows.map(item => ({
      value: item.id,
      label: item.stationName
    }));
  } catch (error) {
    console.error("获取站点列表失败", error);
  }
}

// 查询列表
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams.value,
      stationId: queryParams.value.id,
      orderByColumn: 'createTime',
      isAsc: 'desc'
    };
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0];
      params.endTime = dateRange.value[1];
    }

    console.log('查询参数:', params);
    const res = await listRecord(params);
    
    // 在前端处理65岁及以上的过滤
    if (params.ageFilter === '65+') {
      recordList.value = res.rows.filter(item => calculateAge(item.birthday) >= 65);
      total.value = recordList.value.length;
    } else {
      recordList.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error("获取刷卡记录失败", error);
  } finally {
    loading.value = false;
  }
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    idCard: undefined,
    ageFilter: ''
  };
  dateRange.value = [];
  getList();
}

// 查看按钮操作
const handleView = async (row) => {
  try {
    if (!row.id) {
      ElMessage.error("记录ID不能为空");
      return;
    }
    const res = await getRecord(row.id);
    form.value = res.data;
    open.value = true;
  } catch (error) {
    console.error("获取刷卡记录详情失败", error);
    ElMessage.error("获取详情失败");
  }
};

// 导出按钮操作
const handleExport = async () => {
  try {
    loading.value = true;
    const params = {
      ...queryParams.value,
      stationId: queryParams.value.id,
      pageNum: 1,
      pageSize: 10000,
      orderByColumn: 'createTime',
      isAsc: 'desc'
    };
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0];
      params.endTime = dateRange.value[1];
    }

    console.log('导出参数:', params);
    const res = await listRecord(params);
    
    // 在前端处理65岁及以上的过滤
    let exportData = res.rows;
    if (params.ageFilter === '65+') {
      exportData = res.rows.filter(item => calculateAge(item.birthday) >= 65);
    }

    if (!exportData || exportData.length === 0) {
      ElMessage.warning("没有数据可导出");
      return;
    }

    const { export_json_to_excel } = await import('@/vendor/Export2Excel')
    
    const tHeader = ['站点名称', '姓名', '身份证号', '性别', '民族', '年龄', '住址', '输入方式', '刷卡时间']
    const filterVal = ['stationName', 'name', 'idNumber', 'gender', 'nation', 'birthday', 'address', 'inputMethod', 'createTime']
    const data = formatJson(filterVal, exportData)

    export_json_to_excel({
      header: tHeader,
      data,
      filename: '刷卡记录',
      autoWidth: true,
      bookType: 'xlsx'
    })

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败：" + error.message);
  } finally {
    loading.value = false;
  }
}

// 格式化 JSON 数据
const formatJson = (filterVal, jsonData) => {
  return jsonData.map(v => filterVal.map(j => {
    if (j === 'createTime') {
      return parseTime(v[j])
    } else if (j === 'birthday') {
      // 导出时计算年龄
      return calculateAge(v[j])
    } else if (j === 'inputMethod') {
      // 格式化输入方式
      return v[j] === 0 ? '设备采集' : '手动输入'
    } else {
      return v[j] || ''
    }
  }))
}

// 计算年龄的函数
const calculateAge = (birthday) => {
  if (!birthday) return '';
  const birthDate = new Date(birthday);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
}

// 页面加载时获取数据
onMounted(() => {
  getStationOptions();
  getList();
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
/* 弹窗底部样式 */
.dialog-footer {
  padding: 20px;
  text-align: right;
}

/* 站点名称样式 */
.detail-header {
  display: flex;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}

.detail-header .label {
  width: 120px;
  background-color: #f5f7fa;
  padding: 12px 20px;
  border-right: 1px solid #dcdfe6;
  font-weight: bold;
  color: #606266;
}

.detail-header .content {
  flex: 1;
  padding: 12px 20px;
}

/* 基本信息和照片布局 */
.detail-content {
  display: flex;
  margin: 10px 0;
  gap: 10px;
}

.left-info {
  flex: 1;
}

/* 基本信息样式 */
.basic-info {
  border: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
}

.info-row {
  display: flex;
  height: 47px;
}

.info-row:not(:last-child) {
  border-bottom: 1px solid #dcdfe6;
}

.info-row .label {
  width: 120px;
  background-color: #f5f7fa;
  padding: 12px 20px;
  border-right: 1px solid #dcdfe6;
  font-weight: bold;
  color: #606266;
  display: flex;
  align-items: center;
}

.info-row .value {
  flex: 1;
  padding: 12px 20px;
  display: flex;
  align-items: center;
}

/* 照片区域样式 */
.right-photo {
  width: 200px;
  height: 141px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.id-photo {
  max-width: 100%;
  max-height: 141px;
  object-fit: contain;
}

/* el-descriptions 样式调整 */
:deep(.el-descriptions__body) {
  width: 100%;
}
</style> 